package com.appcheck.recording.listener.impl;

import java.lang.reflect.Field;

import android.view.View;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.appcheck.recording.ListenerManager;
import com.appcheck.recording.WidgetHelper;
import com.appcheck.recording.action.impl.ItemSelectedAction;
import com.appcheck.recording.listener.AbstractListener;
import com.appcheck.recording.utils.Logger;

public class ItemSelectedListener extends AbstractListener implements
		OnItemSelectedListener {
	
	public ItemSelectedListener(View paramView) {
		super(paramView, AdapterView.class, OnItemSelectedListener.class);
		
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		//不管是不是Spinnner,position和id是一样的,position和parent.getFirstVisiblePosition()是一样的
		//Logger.INFO("parent: " + parent.getClass().getSimpleName() + " view: " + view.getClass().getSimpleName());
		
		ItemSelectedAction itemSelectedAction = new ItemSelectedAction();
		//itemClickAction.setLine(position - parent.getFirstVisiblePosition());
		//这里改为记录相对于ApdaterView的position,以前是减去第一次出现的位置
		itemSelectedAction.setLine(position);
		Logger.INFO("onItemSelected position = " + position + ", id = " + id+ ", " +
				"parent.getPositionForView = " + parent.getPositionForView(view));
		
		itemSelectedAction.setParentResourceName(WidgetHelper.getResourceName(parent));
		ListenerManager.getListenerManager().handleAction(itemSelectedAction);
		if(this.listener != null){
			((AdapterView.OnItemSelectedListener)this.listener).onItemSelected(parent, view, position, id);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		if(this.listener != null){
			((AdapterView.OnItemSelectedListener)this.listener).onNothingSelected(parent);
		}
	}
	
	@Override
	protected final Object getListenerFromView(View paramView, Class viewClass, Class listenerClass) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException{
		Field onItemSelectedListenerField = null;
		(onItemSelectedListenerField = viewClass.getDeclaredField("mOnItemSelectedListener")).setAccessible(true);
		
		Object onItemSelectedListener = null;
		if(onItemSelectedListenerField != null){
			onItemSelectedListener = onItemSelectedListenerField.get(paramView);
			return onItemSelectedListener;
		}
		return null;
		
	}
	

}
